package com.systar.activity.parse;

import com.google.common.eventbus.EventBus;
import com.systar.activity.events.ParsingActivityEvent;
import com.systar.activity.state.FileActivity;

public class TxtLogFileParser extends FileParser
{

	public TxtLogFileParser(FileActivity activity, EventBus eventBus)
	{
		super(activity, eventBus);
	}

	@Override
	public Integer call() throws Exception
	{
		nbInfo = nbWarn = nbErr = 0;
		String line;
		while ((line = activity.getReader().readLine()) != null)
		{
			//Thread.sleep(1);
			if (line.startsWith("INF:"))
				nbInfo++;
			if (line.startsWith("WRN:"))
				nbWarn++;
			if (line.startsWith("ERR:"))
				nbErr++;

			// post event every error or if number of messages exceed SUBMIT_TRIGGER
			boolean submit = (nbErr > 0) || (nbInfo + nbWarn > SUBMIT_TRIGGER);
			if (submit)
			{
				eventBus.post(new ParsingActivityEvent(nbInfo, nbWarn, nbErr, (nbErr > 0) ? line : null));
				nbInfo = nbWarn = nbErr = 0;
			}
		}
		// post event if any message left
		boolean submit = (nbInfo > 0) || (nbWarn > 0) || (nbErr > 0);
		if (submit)
		{
			eventBus.post(new ParsingActivityEvent(nbInfo, nbWarn, nbErr, (nbErr > 0) ? line : null));
		}
		eventBus.post(activity);
		return 0;
	}

}
